package com.qf.aspect;

import com.qf.util.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName MyAspect
 * @Description TODO
 * @Author Windy
 * @Date 2022/8/31 17:35
 * @Version 1.0
 **/
@Component
@Aspect
public class MyAspect {

    @Autowired
    TransactionManager tansaction;

    @Before(value = "execution(* com.qf.service.impl.AccountServiceImpl.transfer(..))")
    /**
     * 前置通知
     */
    public void before() {
//        System.out.println("begin");
        //开启事务
        tansaction.beginTransaction();
    }

    @After(value = "execution(* com.qf.service.impl.AccountServiceImpl.transfer(..))")
    /**
     * 后置通知
     */
    public void after_returning() {
        //提交事务
        tansaction.commitTransaction();
    }

//    @Around(value = "execution(* com.qf.service.impl.AccountServiceImpl.transfer(..))")
    /**
     * 环绕通知
     */
    public void around(ProceedingJoinPoint pjp)  {
        System.out.println("begin");
        tansaction.beginTransaction();
        try {
            pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        System.out.println("end");
        tansaction.commitTransaction();
    }

    @AfterThrowing(value = "execution(* com.qf.service.impl.AccountServiceImpl.transfer(..))")
    /**
     * 抛出异常通知
     */
    public void afterThrow() {
        //异常时回滚事务
        tansaction.rollbackTransaction();
    }
    @AfterReturning(value = "execution(* com.qf.service.impl.AccountServiceImpl.transfer(..))")
    /**
     * 最终通知
     */
    public void after() {
        //关闭链接
        tansaction.releaseTransaction();
    }
}
